class School < ActiveRecord::Base
  acts_as_taggable
  
  # edu_type
  # 1 => 小学
  # 2 => 中学
  # 3 => 临时安置点
  
  belongs_to :submitor, :class_name => 'User', :foreign_key => 'submitor_id'
  belongs_to :area
  has_many :photos
  has_many :students
  has_many :comments, :class_name => 'SchoolComment', :dependent => :destroy
  
  validates_presence_of :title, :address, :area_id
  
  format_attribute :advice
  
  def editable_by?(user)
    if is_meta?
      return user!=:false
    else
      if is_validate?
        return user!=:false && (user.is_school_admin?)
      else
        return user!=:false && (user.is_school_admin? || user.id==submitor_id)
      end
    end
  end
  
  def visited_by(user)
    visited = Visited.find(:first, :conditions => {:school_id => id, :user_id => user.id})
    if visited.nil?
      return :false
    else
      return visited.visit_at.to_s
    end
  end 
  
  def build_tags
    tags_arr = (books_need + stationaries_need + sports_need + clothes_need + accessories_need + classes_need + teachers_need + others_need).split(" ").to_a
    tags_arr.collect {|t| t.gsub!(" ", "")}
    tags_arr
  end
  
  def self.submitted_by(user, is_validate=true)
    find(:all, :conditions => {:is_hidden => false,
                               :is_validate => is_validate,
                               :submitor_id => user.id}, :order => "schools.updated_at desc",
               :select => "id, title, updated_at")
  end
end
